package com.cxs.shopstore.service.impl;

import com.cxs.shopstore.es.ESTemplete;
import com.cxs.shopstore.models.Good;
import com.cxs.shopstore.mapper.GoodMapper;
import com.cxs.shopstore.service.GoodDataPullService;
import com.cxs.shopstore.service.GoodService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cxs
 * @since 2021-05-06
 */
@Service
public class GoodServiceImple extends ServiceImpl<GoodMapper, Good> implements GoodService {
    @Autowired
    private ESTemplete esTemplete;
    @Autowired
    private GoodDataPullService goodDataPullService;

    /**
     * 商家后台搜索添加商品
     * @param keyword
     * @param page
     * @return
     */
    @Override
    public List<Good> searchGood(String keyword,int page) {
        List<Good> list = new ArrayList<>();
        //如果es服务器能查询到数据，返回查询结果集
        if(esTemplete.highlightSearch(keyword).size() > 0){
            list = esTemplete.highlightSearch(keyword);
        }else{
            //否则，从京东爬取数据
            list = goodDataPullService.catchDataToList(keyword, page);
            try {
                //将爬取到的数据添加至es
                esTemplete.bluksave(esTemplete.changeList(list));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return list;
    }
    //搜索历史，es中所有数据
    @Override
    public List<Good> selectall() {
        return esTemplete.matchall();
    }
}
